<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <style>
        table {
            margin: 0 auto;
            width: 60%;
            border: 2px solid #aaa;
            border-collapse: collapse;
        }

        table th, table td {
            border: 2px solid #aaa;
            padding: 5px;
        }
        td{
            text-align: center;
        }
        h1{
            width: 100%;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>商品</h1>
    <table border="1">
        <tr>
            <th>商品</th>
            <th>单价</th>
            <th>库存</th>
            <th>评率</th>
        </tr>
        <tr>
            <td>12</td>
            <td>12</td>
            <td>12</td>
            <td>12</td>
            <td align="center"><input type="button" value="加入购物车"
                onclick="add_shoppingcart(this);" /></td>
        </tr>
    </table>

    <h1>购物车</h1>
    <table>
        <thead>
            <tr>
                <th>商品</th>
                <th>单价(元)</th>
                <th>数量</th>
                <th>金额(元)</th>
                <th>删除</th>
            </tr>
        </thead>
        <tbody id="goods">

        </tbody>
</body>
<script>
    function add_shoppingcart(btn){
        var name = $(btn).parent().siblings().eq(0).html();
        var price = $(btn).parent().siblings().eq(1).html();
        var $tr = $('<tr>'
            + '<td>' + name + '</td>'
            + '<td>'+ price + '</td>'
            + '<td align="center">' + '<input type="button" value="-" onclick="decrease(this);"/>'
            + '<input type="text" size="3" readonly value="1"/>'
            + '<input type="button" value="+" onclick="increase(this);"/>'
            + '</td>'
            + '<td>' + price + '</td>'
            + '<td align="center"><input type="button" value="删除" onclick="del(this);"/></td>'
            + '</tr>');
    $("#goods").append($tr);
    sum();
    }
    
    function del(btn) {
        $(btn).parent().parent().remove();
        sum();
    };

    function increase(btn) {
        var amount = $(btn).prev().val();
        $(btn).prev().val(++amount);
        var price = $(btn).parent().prev().html();
        var mny = price * amount;
        $(btn).parent().next().html(mny);           
        sum();
    };
    function decrease(btn) {
        var amount = $(btn).next().val();
        if (amount <= 1) {
            return;
        }
        $(btn).next().val(--amount);
        var price = $(btn).parent().prev().html();
        var mny = price * amount;
        $(btn).parent().next().html(mny);
        sum();
    };

</script>
</html>